<template>
  <div style="width: 100%;height: 350px;position: relative" v-loading="loading">
    <div class="chart-div" ref="chart"></div>
    <div style="position: absolute;right: 70px;top:3px;cursor: pointer">
      <div class="mark-icon" style="display: block" @click="chartMarkLine">
        <i class="el-icon-discount" style="font-size:20px" :class="[isMarkLine?'active':'unactive']"></i>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts';
import {getVibFFT} from "@/api/raw";

export default {
  name: 'fftChart',
  props: ['vibForm'],
  data() {
    return {
      loading: false,
      // 图表对象
      chart: null,
      // 图表配置
      chartOptions: null,
      // 图表数据
      chartData: null,
      // 倍频线标注状态
      isMarkLine: false,
      // 波形时间
      eventTime: null
    }
  },
  watch: {
    vibForm: {
      handler: function (val) {
        this.$nextTick(() => {
          this.getData()
        })
      },
      deep: true, // 深度监听
      immediate: true
    },
    "isMarkLine": function (val) {
      this.$nextTick(() => {
        if (val) {
          this.chart.getZr().on('click', this.handleClick);
        } else {
          this.chart.getZr().off("click", this.handleClick);
        }
      })
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', () => {
      this.chart.resize()
    })
  },
  methods: {
    /**
     * 获取图表数据
     */
    getData() {
      this.loading = true;
      this.chartData = null;
      if (!this.vibForm.date || !this.vibForm.eventTime) {
        this.loadData('x');
        return;
      }
      getVibFFT(this.vibForm).then(res => {
        this.chartData = res.data;
        this.loadData(this.vibForm.axial == null ? 'x' : this.vibForm.axial)
        this.chart.resize()
      }).catch(err => {
        this.showEmptyChart()
      })
    },
    showEmptyChart() {
      let yName = this.vibForm.physicalType === 'acc' ? 'g' : 'mm/s';
      let xName, title;
      if (this.vibForm.signalType === 'ang') {
        xName = '阶次';
        title = "阶次谱"
      } else {
        xName = '频率 - Hz';
        title = "频域"
      }
      this.chartOptions.title.text = title;
      this.chartOptions.yAxis[0].name = yName;
      this.chartOptions.xAxis[0].name = xName;
      this.chartOptions.xAxis[0].data = [];
      this.chartOptions.series[0].data = [];
      this.chart.setOption(this.chartOptions, true);
      this.chart.showLoading({
        text: '暂无数据',
        showSpinner: false,
        textColor: '#808080',
        // maskColor: 'rgba(255, 255, 255, .6)',
        fontSize: '26px',
        fontWeight: '400'
      })
      this.loading = false;
    },
    /**
     * 加载图表
     * @param axial
     */
    loadData(axial) {
      if (this.chartData == null) {
        this.showEmptyChart();
        return;
      }
      let yName = this.vibForm.physicalType === 'acc' ? 'g' : 'mm/s';
      let xName, title;
      if (this.vibForm.signalType === 'ang') {
        xName = '阶次';
        title = "阶次谱"
      } else {
        xName = '频率 - Hz';
        title = "频域"
      }
      this.eventTime = this.chartData.timestamp;
      let data = [];
      for (let a in this.chartData[axial]) {
        let array = [parseInt(a), this.chartData[axial][a]];
        data.push(array);
      }
      this.chartOptions.title.text = title;
      this.chartOptions.yAxis[0].name = yName;
      this.chartOptions.xAxis[0].name = xName;
      this.chartOptions.xAxis[0].data = this.chartData.t;
      this.chartOptions.series[0].data = data;
      this.chartOptions.series[0].markLine.data = [];
      this.chart.setOption(this.chartOptions, true);
      this.chart.hideLoading()
      this.loading = false;
    },
    /**
     * 初始化图表对象
     */
    initChart: function () {
      if (this.chart !== null && this.chart !== undefined) {
        this.chart.dispose();
      }
      this.chartOptions = {
        title: {
          text: '频域',
          textStyle: {
            fontStyle: '',
            color: '#333',
            fontWeight: 'normal',
            fontSize: 14
          },
          left: 0,
        },
        toolbox: {
          show: true,
          height: 0,
          top: -5,
          right: 10,
          feature: {
            // myMarkLineTool: {
            //   show: true,
            //   title: "倍频线",
            //   icon: "image://",
            //   onclick: function () {
            //     self.chartMarkLine();
            //   }
            // },
            dataZoom: {
              yAxisIndex: 'none',
            },
            // saveAsImage: {
            //   pixelRatio: 2,
            //   backgroundColor: "#1c1c1E"
            // }
          },
          itemSize: 18,
          iconStyle: {
            borderColor: "#000000"
          }
        },
        dataZoom: [{
          type: 'inside',
          show: true
        }],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          crossStyle: {
            color: "#999",
          },
          showContent: true,
        },
        xAxis: [
          {
            name: '频率 - Hz',
            nameLocation: 'center',
            nameTextStyle: {
              padding: [10, 0, 0, 0]
            },
            type: 'category',
            // interval: 300,
            min: 0,
            axisTick: {
              alignWithLabel: true,
              lineStyle: {
                color: "#3c3f41",
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#3c3f41",
              }
            },
            splitLine: {
              lineStyle: {
                color: "#c6c6c6"
              }
            },
            axisPointer: {
              lineStyle: {
                color: "#E6A23C"
              },
              label: {
                formatter: function (params) {
                  return params.value;
                  // if (params.seriesData[0].data) {
                  //   // return "[x]" + params.value + "  [y]" + params.seriesData[0].data[1] + "m/s^2";
                  //   return params.value;
                  // } else {
                  //   return null;
                  // }
                },
                padding: [5, 14],
                margin: 0,
                backgroundColor: "#E6A23C"
              },
            },
            axisLabel: {
              show: true,
              // interval: 499
            }
          }
        ],
        yAxis: [
          {
            name: 'g',
            nameLocation: 'end',
            type: 'value',
            boundaryGap: ["20%", '20%'],
            splitLine: {
              lineStyle: {
                color: "#f0f0f0"
              }
            },
            min: 0,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#202c3a"
              }
            },
            axisLabel: {
              inside: false,
            },
            axisPointer: {
              lineStyle: {
                color: "#E6A23C"
              },
              label: {
                backgroundColor: "#E6A23C"
              }
            },
            axisTick: {
              inside: true,
            }
          }
        ],
        grid: {
          top: 50,
          bottom: 20,
          left: 8,
          right: 16,
          containLabel: true,
        },
        series: [
          {
            type: 'line',
            // itemStyle: {
            //   color: 'rgb(255,10,10)'
            // },
            symbol: "none",
            xAxisIndex: 0,
            lineStyle: {
              width: 1,
              color: "#409EFF",
            },
            emphasis: {
              lineStyle: {
                width: 1
              }
            },
            markLine: {
              symbol: 'circle',
              label: {
                normal: {
                  position: 'end',
                  formatter: function (e) {
                  }
                }
              },
              data: []
            }
          }
        ]
      };
      this.chart  = echarts.init(this.$refs.chart);
      this.chart.setOption(this.chartOptions);
      let that = this;
      onOrientationChange(function () {
        that.chart.resize();
      });
    },
    /**
     * 倍频线标线
     */
    chartMarkLine() {
      this.isMarkLine = !this.isMarkLine;
    },
    /**
     * 倍频线标注
     * @param params
     */
    handleClick(params) {
      let self = this;
      var option = this.chart.getOption();
      const pointInPixel = [params.offsetX, params.offsetY]
      // 使用 convertFromPixel方法 转换像素坐标值到逻辑坐标系上的点。获取点击位置对应的x轴数据的索引值，借助于索引值的获取到其它的信息
      let pointInGrid = this.chart.convertFromPixel({seriesIndex: 0}, pointInPixel);
      let xIndex = Math.round(pointInGrid[0]);
      let dataX_length = self.chartData[this.vibForm.axial].length;
      let data_r = [];
      //截取选取点前后各50个节点的数据
      let check_arr = option.series[0].data.slice(xIndex - 50 < 0 ? 0 : xIndex - 50, xIndex + 50 > dataX_length - 1 ? dataX_length - 1 : xIndex + 50);
      let maxIndex = this.computedMaxIndex(check_arr) + (xIndex - 50 < 0 ? 0 : xIndex - 50);
      if (dataX_length > 0) {
        let unitStr = 'Hz';
        for (let i = 0; i < dataX_length / maxIndex; i++) {
          let obj = {
            name: (i + 1) + "X" + " " + option.xAxis[0].data[maxIndex * (i + 1)] + unitStr,
            xAxis: maxIndex * (i + 1)
          };
          data_r.push(obj);
        }
      }
      option.series[0].markLine.data = data_r;
      self.chart.clear();
      self.chart.setOption(option);
      // this.$emit('toolBtnRet');
      // this.isMarkLine = false;
      // this.chart.getZr().off("click", this.handleClick);
    },
    /**
     * 获取数组最大值下标
     * @param arr
     * @returns {number}
     */
    computedMaxIndex(arr) {
      let index = 0;
      function greater(arr, idx) {
        if (arr.every(item => item[1] <= arr[idx][1])) {
          // console.log(arr[idx]);
          index = idx;
          return idx;
        }
        greater(arr, idx + 1);
      }
      greater(arr, 0)
      return index;
    }
  }
}
//图表重加载
var onOrientationChange = function (cb) {
  var evt = "onorientationchange" in window ? "orientationchange" : "resize";
  window.addEventListener(evt, resize, true);

  function resize(fals) {
    if (window.orientation == 0 || window.orientation == 180) {
      cb('v');
    } else {
      cb('h');
    }
  }

  resize(true);
}
</script>
<style scoped>
.chart-div {
  width: 100%;
  height: 100%;
}

.mark-icon .active {
  color: #409EFF;
}

.mark-icon:hover i {
  color: #409EFF;
}
</style>